package com.sneaker.shower.common;

import org.springframework.util.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;

public abstract class AES {
    private static final String key = "sneaker.club";

    public static String encrypt(String sSrc) throws Exception {

        String md5 = DigestUtils.md5DigestAsHex(key.getBytes());

        byte[] raw = md5.substring(0, 8).getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        SecureRandom secureRandom = new SecureRandom(raw);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, secureRandom);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }

    // 解密
    public static String decrypt(String sSrc) throws Exception {
        // 判断Key是否正确

        String md5 = DigestUtils.md5DigestAsHex(key.getBytes());

        byte[] raw = md5.substring(0, 8).getBytes();
        SecureRandom secureRandom = new SecureRandom(raw);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, secureRandom);
        byte[] encrypted1 = Base64.getDecoder().decode(sSrc);//先用base64解密
        byte[] original = cipher.doFinal(encrypted1);
        return new String(original, StandardCharsets.UTF_8);
    }

}
